"""Device Bridge Frontend Panel."""

import logging
from homeassistant.core import HomeAssistant
from homeassistant.components.frontend import async_register_built_in_panel
from homeassistant.components.http import HomeAssistantView
from aiohttp import web

_LOGGER = logging.getLogger(__name__)


class DeviceBridgePanelView(HomeAssistantView):
    """Device Bridge Panel View."""

    url = "/device_bridge_panel"
    name = "device_bridge_panel"
    requires_auth = True

    async def get(self, request):
        """Serve the device bridge panel."""
        html_content = """
<!DOCTYPE html>
<html>
<head>
    <title>Device Bridge - 设备桥接</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body { 
            font-family: Arial, sans-serif; 
            margin: 20px; 
            background-color: #f5f5f5;
        }
        .container { 
            max-width: 500px; 
            margin: 0 auto; 
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
        }
        .qr-code {
            max-width: 300px;
            margin: 20px auto;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .generate-btn {
            background-color: #03a9f4;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            margin: 20px 10px;
        }
        .generate-btn:hover {
            background-color: #0288d1;
        }
        .loading {
            padding: 40px;
            color: #666;
            font-size: 16px;
        }
        .no-qr {
            padding: 40px;
        }
        .success {
            color: #4caf50;
            font-weight: bold;
            margin-top: 15px;
            padding: 10px;
            background-color: #e8f5e8;
            border-radius: 4px;
        }
        .error {
            color: #f44336;
            padding: 20px;
            background-color: #ffebee;
            border-radius: 4px;
            margin: 10px 0;
        }
        input[type="text"] {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin: 10px;
            font-size: 14px;
            width: 150px;
        }
        h1 {
            color: #333;
            margin-bottom: 10px;
        }
        p {
            color: #666;
            margin-bottom: 30px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🌉 Device Bridge</h1>
        <p>扫描二维码连接设备</p>
        
        <div id="qr-container" class="loading">
            正在加载二维码...
        </div>
        
        <div>
            <input type="text" id="clientName" placeholder="客户端名称" value="mobile_app">
            <br>
            <button onclick="generateNewQRCode()" class="generate-btn">🔄 重新生成二维码</button>
        </div>
    </div>

    <script>
        // 页面加载时自动加载二维码
        window.onload = function() {
            loadQRCode();
        };
        
        async function loadQRCode() {
            try {
                const response = await fetch('/api/device_bridge/qr_code');
                const data = await response.json();
                
                if (data.qr_code_base64) {
                    document.getElementById('qr-container').innerHTML = `
                        <img src="data:image/png;base64,${data.qr_code_base64}" 
                             class="qr-code" alt="Device Bridge QR Code">
                    `;
                } else {
                    document.getElementById('qr-container').innerHTML = `
                        <div class="no-qr">
                            <p>暂无二维码</p>
                            <button onclick="generateNewQRCode()" class="generate-btn">生成二维码</button>
                        </div>
                    `;
                }
            } catch (error) {
                console.error('加载二维码失败:', error);
                document.getElementById('qr-container').innerHTML = `
                    <div class="error">
                        <p>加载二维码失败</p>
                        <button onclick="generateNewQRCode()" class="generate-btn">重新生成</button>
                    </div>
                `;
            }
        }
        
        async function generateNewQRCode() {
            try {
                document.getElementById('qr-container').innerHTML = `
                    <div class="loading">正在生成二维码...</div>
                `;
                
                const clientName = document.getElementById('clientName').value || 'mobile_app';
                
                const response = await fetch('/api/device_bridge/qr_code', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        client_name: clientName
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    document.getElementById('qr-container').innerHTML = `
                        <img src="data:image/png;base64,${data.qr_code_base64}" 
                             class="qr-code" alt="Device Bridge QR Code">
                        <div class="success">✅ 二维码已生成</div>
                    `;
                    
                    // 3秒后移除成功消息
                    setTimeout(() => {
                        const successMsg = document.querySelector('.success');
                        if (successMsg) {
                            successMsg.remove();
                        }
                    }, 3000);
                } else {
                    throw new Error(data.error || '生成失败');
                }
            } catch (error) {
                console.error('生成二维码失败:', error);
                document.getElementById('qr-container').innerHTML = `
                    <div class="error">
                        <p>生成二维码失败: ${error.message}</p>
                        <button onclick="generateNewQRCode()" class="generate-btn">重试</button>
                    </div>
                `;
            }
        }
    </script>
</body>
</html>
        """

        return web.Response(text=html_content, content_type="text/html")


async def async_setup_frontend(hass: HomeAssistant):
    """Set up the frontend."""
    # 注册HTTP视图
    hass.http.register_view(DeviceBridgePanelView())

    # 注册侧边栏面板 - 使用iframe方式
    try:
        hass.components.frontend.async_register_built_in_panel(
            "iframe",  # 使用iframe类型
            "设备桥接",  # 标题
            "mdi:bridge",  # 图标
            "device_bridge",  # URL路径
            {"url": "/device_bridge_panel"},  # iframe配置
            require_admin=False,
        )

        _LOGGER.info("Device Bridge panel registered in sidebar")

    except Exception as e:
        _LOGGER.error(f"Failed to register Device Bridge panel: {e}")
        _LOGGER.info("Device Bridge panel available at /device_bridge_panel")
